{include file="admin@public/header" /}

<link rel="stylesheet" href="/public/static/admin/easyui/layui-v2.6.8/css/layui.css">
<!-- <link rel="stylesheet" type="text/css" href="/public/static/admin/easyui/jeasyui/themes/icon.css"> -->
<link href="/public/static/admin/blue/bills.css" rel="stylesheet" type="text/css">
{include file="admin@public/css" /}

<div class="wrapper">
  <div class="mod-toolbar-top mr0 cf dn" id="toolTop"></div>
  <div class="bills cf">
    <div class="con-header layui-form">
      <dl class="cf">
        <dd class="mr20">
          <label><span class="red">*</span>供应商:</label>
          <span class="ui-combo-wrap" id="customer" style="width: 198px;">
            <i class="ui-icon-ellipsis" onclick="chooseSupplier(1,0)"></i>
            <input type="text" name="" class="input-txt" autocomplete="off" value="" data-ref="date"
              style="width: 188px;">
          </span>
          <input type="hidden" id="customerid" value="" autocomplete="off" readonly="">
        </dd>
        <dd class="mr20">
          <label>单据日期:</label>
          <input type="date" id="dj_time" class="ui-input " value="{$today}" style="width: 125px;">
        </dd>
        <dd class="mr20">
          <label>交货日期:</label>
          <input type="date" id="jh_time" class="ui-input" value="{$today}" style="width: 125px;">
        </dd>
        <dd id="classes" class="mr20">
          <input type="radio" name="type" value="0" title="购货" checked="">
          <input type="radio" name="type" value="1" title="退货">
        </dd>
 
        {include file="admin@public/order/change_sn" /}
       

      </dl>
      <hr class="hrcls">
    </div>

    <div class="wrapper_con">
      <!-- <div class="cf mb10">
      <div class="fl">
      <span  id="config" class="ui-config"><a href="#" class="ui-icon-config-new"></a>列设置</span>
      <span><label>扫描枪录入</label><span id="barCodeInsert" class="close"><span class="ui-icon-circle"></span></span></span>
      </div>
      <div class="fr">
      <span class="circle-link-order linkToCheck"><a href="#" class="icon-link-order"></a>历史单据</span>
      </div>
    </div> -->
      <span id="config" class="ui-config"><a href="#" class="ui-icon-config-new"></a></span>
      <div class="grid-wrap">
        <table id="grid"></table>
        <div id="page"></div>
      </div>
      <div class="cf" id="bottomField">
        <span id="groupBtn">
          <a id="import" class="ui-btn ui-btn-search" onclick="onImport('/admin/basic/batch_import.html','批量导入商品','925px','576px')">批量导入</a>
          <a id="savaAndAdd" class="ui-btn ui-btn-sp">保存并新增</a>
          <a id="save" class="ui-btn">保存</a>
          <a class="ui-btn"  id="o_shenhe">审核</a>
        </span>
      </div>
      <div id="mark"></div>
    </div>

    <div class="con-footer cf">
      <div class="mb10">
        <textarea type="text" id="note" class="ui-input ui-input-ph" placeholder="暂无备注信息"></textarea>
      </div>
      {include file="admin@public/yh" /}

      
      <ul id="user-field">
        <li class="udfLink"><a class="user-field">自定义字段</a></li>
      </ul>
      <ul id="user-field">
        <v-input v-for="(item, index) in udfData" :title="item.name" :type="item.type" v-model="item.value"
          :items="item.items" :metaid="item.metaId" :readonly="isChecked" :key="item.metaId"></v-input>
        <li class="udfLink">
          <v-user-field :transtype="transtype" :udfdata="udfData"></v-user-field>
        </li>
      </ul>

      <div class="cf fr">
        <a class="linkToCheck ui-btn-bill ui-btn-add mr20"
          onclick="addPage('/scm/invPo/index.html','purchaseinvPo','购货订单记录')"><span></span>历史单据</a>
        <a href="#" id="operaLog" class="ui-btn">操作日志</a>
      </div>
    </div>

    <!-- 操作日志 -->
    <ul id="operaLogBox" class="shadow opera-log-box " style="position: absolute;z-index: 999; display: none;">
      <li>
        <span class="fl" style="margin-right: 50px;"><label>制单人：</label><span id="userName"
            style="margin-left: 12px;"><span open-data="" title="{$admin.name}">{$admin.name}</span></span></span>
      </li>
    
    </ul>


    <div id="initCombo" class="dn">
      <input type="text" class="textbox goodsAuto" name="goods" autocomplete="off">
      <input type="text" class="textbox storageAuto" name="storage" autocomplete="off">
      <input type="text" class="textbox unitAuto" name="unit" autocomplete="off">
      <input type="text" class="textbox priceAuto" name="price" autocomplete="off">
      <input type="text" class="textbox skuAuto" name="price" autocomplete="off">
    </div>


  </div>

  <!-- 可用库存弹窗 -->
  <div id="snapshotTipsBox" class="shadow target_box dn pcnone"
    style="width: 275px; position: absolute; left: 662px; top: 171.891px; z-index: 999;display: block;">
    <div style="line-height: 20px;font-size: 13px;">
      <p><strong>1.</strong>可用库存的取值逻辑是取单据新增时选择商品+仓库的可用库存,取出来之后会进行保存,后期<span
          style="color: #ff4136;">不会随着商品的库存变化而自动发生变化,如需查看库存请点击仓库前面的放大镜按钮查看</span></p>
      <p><strong>2.</strong>举例:商品a在仓库a的即时库存10,可用库存9</p>
      <p>&nbsp;&nbsp;<strong>1)</strong>新增销货单,选择商品a和仓库a,可用库存显示的是9,单据保存</p>
      <p>&nbsp;&nbsp;<strong>2)</strong>新增购货单选择商品a和仓库a,入库数量10,单据审核</p>
      <p>&nbsp;&nbsp;<strong>3)</strong>找到刚刚保存的销货单,查看商品a和仓库a的可用库存显示是9,请注意这里不会是19,因为可用库存不会重新获取。</p>
    </div>
  </div>

  <!-- 仓库弹窗 -->
  <div id="storageBox1" class="shadow target_box dn pcnone"
    style="position: absolute; left: 705.65px; top: 133.688px; z-index: 999; display: block;">
    <ul>
      <li data-id="129127919158566" data-name="默认仓库" onclick="closeStorage(1)">CK001 默认仓库</li>
    </ul>
  </div>

  <!-- 折扣率弹窗 -->
  <div id="storageBox2" class="shadow target_box dn pcnone"
    style="position: absolute; left: 896.641px; top: 116.891px; z-index: 999; display: block;">
    <p>批量填充折扣率</p>
    <p><input type="text" style="width:100px;">% &nbsp;&nbsp;&nbsp;&nbsp;
      <input type="button" value="确定" style="float:right" onclick="closeStorage(2)">
    </p>
  </div>

  <!-- 折扣额弹窗 -->
  <div id="storageBox3" class="shadow target_box dn pcnone"
    style="position: absolute; left: 1015px; top: 146.891px; z-index: 999; display: block;">
    <p>输入折扣额,将会自动分摊到每个商品</p>
    <p><input type="text" style="width:100px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <input type="button" value="确定" style="float:right" onclick="closeStorage(3)">
    </p>
  </div>

  {include file="admin@public/order/choose_good" /}

  {include file="admin@public/order/choose_store" /}

</div>


<script type="text/javascript">
  var Pdata;
  var edit_row = 0;
  var edit_col = 0;
  var row_id = 0;
  var col_name = 0;

  $(document).ready(function () {

    // 跳转打开新标签页
    $(".ta").click(function () {
      var tabid = $(this).attr('tabid');
      var tabTxt = $(this).attr('tabTxt');
      var _href = $(this).attr('_href');
      parent.tab.addTabItem({
        tabid: tabid,
        text: tabTxt,
        url: _href
      })
    });

    var outhtml = '';
    var inhtml = ' ';
    var goods = '<span class="red">*</span>商品<label> -- 扫描枪录入</label><span id="barCodeInsert" class="open" onclick="smq();"><span class="ui-icon-circle"></span></span>';
    var batch = '<span class="red">*</span>仓库<small id="batchStorage1" onclick="batchBtn(1);" class="btns">批量</small>';
    var inventory = '可用库存<img src="/public/static/admin/css/img/help.png" style="width: 20px;display: inline-block;margin-left: 5px;" onclick="snapshotTipsFun()" id="snapshotTipsBtn"/>';
    var zk_lv = '折扣率(%)<small id="batchStorage2" onclick="batchBtn(2);" class="btns">批量</small>';
    var zk_e = '折扣额<small id="batchStorage3" onclick="batchBtn(3);" class="btns">批量</small>';


    $("#grid").jqGrid({
      url: '/scm/purchase/edit.html?ajax=100&xxdd_ids={$xxdd_ids}&is_znbh={$is_znbh}',
      datatype: "json",//数据来源，本地数据（local，json,jsonp,xml等）
      height: '90%',//高度，表格高度。可为数值、百分比或'auto'
      colNames: ['操作', '', goods, '商品备注', '单位', batch, inventory, '<span class="red">*</span>数量', '基本单位', '基本数量', '购货单价', '含税单价', zk_lv, zk_e, '金额', '税率(%)', '税额', '价税合计', '备注', '关联销货订单号', '商品ID', '仓库id', '单位id', "基本单位id",'xxdd_id'],
      colModel: [
        { name: '', index: 'id', width: 70, formatter: cLink, align: "center" },
        { name: 'id', index: 'id', width: 40, hidden: true },
        {
          name: "good_name",
          label: "商品",
          width: 300,
          title: !0,

          classes: "goods",
          editable: true,
          edittype: "custom",
          editoptions: {
            custom_element: function (t, e) {
              //return $(".goodsAuto")[0]
              var ht = $("#elem_goods");
              $("#pelem_goods").html('<div class="pr" id="elem_goods"><input type="text" class="textbox  customelement" name="good_name" autocomplete="off" ><span class="ui-icon-ellipsis"></span></div>');
              return ht;
            },
            custom_value: function (t, e, a) {
              var ad = $("#good_name").val();
              $("#good_name").val("");//重置赋值
              return ad;
            },
            handle: function () {

            },
            trigger: "ui-icon-ellipsis"
          }
        },
        { name: 'good_mark', width: 100, label: "商品备注" },
        { name: 'unit_name', index: '', width: 100, label: "单位" },
        {
          name: "store_name",
          label: '<span class="red">*</span>仓库',
          nameExt: '<small id="batchStorage">批量</small>',
          width: 100,
          link: "inventory",
          editable: !0,
          edittype: "custom",
          editoptions: {
            custom_element: function (t, e) {
             
                $("#p_store_name_details").html('<div class="pr" id="store_name_details"><input value="'+t+'" type="text" class="textbox storageAuto customelement ui-combo-active" name="store_name" autocomplete="off" style="outline: -webkit-focus-ring-color auto 5px;"><span class="ui-icon-triangle-1-s store_name_details"></span></div>');
                return $("#store_name_details");
            },
            custom_value: function (t, e, a) {
              var ba = $("#store_name").val();
              $("#store_name").val("");//重置赋值
              return ba;
            },
            trigger: "ui-icon-triangle-1-s"
          }
        },
        { name: 'use_kc', index: '', width: 80, label: "可用库存", },
        { name: 'shuliang', index: '', width: 80, label: "数量", editable: true },
        { name: 'base_unit_name', index: '', width: 100, label: "基本单位", editable: false },
        { name: 'base_number', index: '', width: 100, label: "基本数量", editable: false },
        { name: 'price', index: '', width: 100, label: "购货单价", editable: true },
        { name: 'hs_price', index: '', width: 100, label: "含税单价", editable: true },
        { name: 'zk_lv', index: '', width: 126, label: "折扣率(%)", editable: true },
        { name: 'zk_e', index: '', width: 126, label: "折扣额", editable: true },
        { name: 'jine', index: '', width: 100, label: "金额", editable: true },
        { name: 'tax_lv', index: '', width: 100, label: "税率", editable: true },
        { name: 'tax_e', index: '', width: 100, label: "税额", editable: true },
        { name: 'total_price', index: '', width: 100, label: "价税合计", editable: true },
        { name: 'mark', index: '', width: 150, label: "备注", editable: true },
        { name: 'xxdd_sn', index: '', width: 150, label: "关联销货订单号", editable: false },
        { name: 'good_id', width: 100, hidden: true },
        { name: 'store_id', width: 100, hidden: true },
        { name: 'unit_id', width: 100, hidden: true },
        { name: 'base_unit_id', width: 100, hidden: true },
        { name: 'xxdd_id', width: 100, hidden: true },
      ],
      cellEdit: true,
      cellurl: '/',
      rowNum: 10,
      rowList: [10, 20, 30],
      sortname: 'id',
      sortorder: "desc",
      pagerpos: "left",//分页位置
      rownumbers: true,
      pgbuttons: true,//翻页按钮
      pagination: true,
      altRows: !0,
      gridview: !0,
      shrinkToFit: !1,
      cellLayout: 8,
      autowidth: !0,
      pager: "#page",
      viewrecords: !0,
      cmTemplate: {
        sortable: !1,
        title: !1
      },
      // 合计
      footerrow: true,
      gridComplete: function () {
        var shuliangs = $("#grid").getCol('shuliang', false, 'sum');
        var base_numbers = $("#grid").getCol('base_number', false, 'sum');
        var zk_es = $("#grid").getCol('zk_e', false, 'sum');
        var jines = $("#grid").getCol('jine', false, 'sum');
        var tax_es = $("#grid").getCol('tax_e', false, 'sum');
        var total_prices = $("#grid").getCol('total_price', false, 'sum');
        $("#grid").footerData('set', { "good_name": '合计', shuliang: shuliangs, base_number: base_numbers, zk_e: zk_es, jine: jines, tax_e: tax_es, total_price: total_prices });
      },
      loadError: function (t, e, i) {
        parent.Public.tips({
          type: 1,
          content: "操作失败了哦，请检查您的网络链接！"
        })
      },
      beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
        col_name = cellname;
        edit_row = iRow;
        edit_col = iCol;
        row_id = rowid;
        var gname = $("#grid").jqGrid("getCell", row_id, 'good_name');
        $("#good_name").val(gname);

      },
      // afterEditCell: function (rowid, cellname, value, iRow, iCol) {
      //   alert("编辑后");
      //   var shuliangs = $("#grid").getCol('shuliang', false, 'sum');
      //   $("#grid").footerData('set', { "good_name": '合计', shuliang: shuliangs});
      // },

      beforeSaveCell: function (rowid, cellname, value, iRow, iCol) {
        edit_row = iRow;
        edit_col = iCol;
        row_id = rowid;

        // 重算
        // step1 (取值)
        var shuliang = parseFloat($("#grid").jqGrid("getCell", row_id, 'shuliang'));
        var price = parseFloat($("#grid").jqGrid("getCell", row_id, 'price'));
        var hs_price = parseFloat($("#grid").jqGrid("getCell", row_id, 'hs_price'));
        var zk_lv = parseFloat($("#grid").jqGrid("getCell", row_id, 'zk_lv'));
        var zk_e = parseFloat($("#grid").jqGrid("getCell", row_id, 'zk_e')).toFixed(2);
        var jine = parseFloat($("#grid").jqGrid("getCell", row_id, 'jine'));
        var tax_lv = parseFloat($("#grid").jqGrid("getCell", row_id, 'tax_lv'));
        var tax_e = parseFloat($("#grid").jqGrid("getCell", row_id, 'tax_e'));
        var total_price = parseFloat($("#grid").jqGrid("getCell", row_id, 'total_price'));


        // 合计的变量
        var shuliangs = parseFloat($("#grid").getCol('shuliang', false, 'sum')).toFixed(2);
        var zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
        var jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
        var tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
        var total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);

        // step2 (计算)
        if (cellname == 'shuliang') {
          $("#grid").jqGrid("setCell", row_id, 'base_number', value);
          zk_e = parseFloat(price / 1 * (zk_lv / 100) * value).toFixed(2);
          jine = parseFloat(price * value - zk_e / 1).toFixed(2);
          tax_e = parseFloat(jine / 1 * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'price') {
          hs_price = parseFloat(price * (1 + (tax_lv / 100))).toFixed(2);
          zk_e = parseFloat(price * (zk_lv / 100) * shuliang).toFixed(2);
          jine = parseFloat(price * shuliang - zk_e).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'hs_price') {
          price = parseFloat(hs_price / (1 + (tax_lv / 100))).toFixed(2);
          zk_e = parseFloat(price / 1 * (zk_lv / 100)).toFixed(2) * shuliang;
          jine = parseFloat(price * shuliang - zk_e).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'zk_lv') {
          zk_e = parseFloat(price / 1 * (zk_lv / 100)).toFixed(2) * shuliang;
          jine = parseFloat(price * shuliang - zk_e).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'zk_e') {
          zk_lv = parseFloat(zk_e / 1 / shuliang / price / 1).toFixed(6) * 100;
          jine = parseFloat(price * shuliang - zk_e / 1).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'jine') {
          price = parseFloat((jine / 1) / (1 - (zk_lv / 100))).toFixed(2) / shuliang;
          hs_price = parseFloat(price / 1 * (1 + (tax_lv / 100))).toFixed(2);
          zk_e = parseFloat(price / 1 * (zk_lv / 100) * shuliang).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'tax_lv') {
          hs_price = parseFloat(price / 1 * (1 + (tax_lv / 100))).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'tax_e') {
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'total_price') {
          jine = parseFloat(total_price / (1 + (tax_lv / 100))).toFixed(2);
          price = parseFloat(jine / (1 - (zk_lv / 100))).toFixed(2) / shuliang;
          hs_price = parseFloat(price / 1 * (1 + (tax_lv / 100))).toFixed(2);
          zk_e = parseFloat(price / 1 * (zk_lv / 100)).toFixed(2) * shuliang;
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        // step3 (赋值)
        $("#grid").jqGrid("setCell", row_id, 'shuliang', shuliang);
        $("#grid").jqGrid("setCell", row_id, 'price', price);
        $("#grid").jqGrid("setCell", row_id, 'hs_price', hs_price);
        $("#grid").jqGrid("setCell", row_id, 'zk_lv', zk_lv);
        $("#grid").jqGrid("setCell", row_id, 'zk_e', zk_e);
        $("#grid").jqGrid("setCell", row_id, 'jine', jine);
        $("#grid").jqGrid("setCell", row_id, 'tax_lv', tax_lv);
        $("#grid").jqGrid("setCell", row_id, 'tax_e', tax_e);
        $("#grid").jqGrid("setCell", row_id, 'total_price', total_price);

        // 计算合计
        if (cellname == 'shuliang') {

          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);

        } else if (cellname == 'zk_e') {

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);

        } else if (cellname == 'jine') {

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);

        } else if (cellname == 'tax_e') {

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);

        } else if (cellname == 'total_price') {

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);

        } else {

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);

        }

        var base_numbers = $("#grid").getCol('base_number', false, 'sum');
        $("#grid").footerData('set', { "good_name": '合计', shuliang: shuliangs, base_number: base_numbers, zk_e: zk_es, jine: jines, tax_e: tax_es, total_price: total_prices });


        // 底部统计
        $('#yh_price').val(total_prices);
        $("#before_yh_price").val(total_prices);
      },
    });


    var mydata = [];
    for (var i = 0; i < 5; i++) {
      var obj = { id: i + 1, good_name: "", goodsmark: ""}
      mydata.push(obj);
    };


    for (var i = 0; i <= mydata.length; i++) {
      jQuery("#grid").jqGrid('addRowData', i + 1, mydata[i]);
    }

  });


  // function addressElem(e, t) {
  //     var addr = $(".address");
  //     //补充.calss
  //     $("#lxdz").html('<div class="pr class"><input type="text" class="textbox address customelement"   autocomplete="off" readonly=""></div>');
  //     return $(addr);

  //   }

  //   function addressValue(e, t, a) {
  //     var ad = $("#lxaddr").val();
  //     $("#lxaddr").val("");//重置赋值
  //     return ad;
  //   }

  //   function addressHandle() {
  //     $(".hideFile").append($(".address").val("").unbind("focus.once"))
  //   }



  $(document).ready(function () {



    // 选择仓库弹窗
    $(".grid-wrap").on("click", ".store_name_details", function (e) {
      var top = $(this).offset().top;
      var left = $(this).offset().left;
      $("#droplist_store").show();
      $("#droplist_store").css({ "top": (top + 25) + "px", "left": (left - 80) + "px" })
    })
    


    // 点击下拉框其他位置隐藏
    $(document).click(function () {
      $("#snapshotTipsBox").addClass("pcnone");
      $("#storageBox1").addClass('pcnone');
      $("#storageBox2").addClass('pcnone');
      $("#storageBox3").addClass('pcnone');
    });
    // 阻止冒泡
    // $(".ctn-wrap,#jqgh_grid_locationName,#jqgh_grid_ck1,#jqgh_grid_discount,#jqgh_grid_deduction").click(function (event) {
    //   event.stopPropagation();
    // });

    



    // 操作日志鼠标移入移除
    $("#operaLog").hover(function () {
      var top = $(this).offset().top;
      // var left = $(this).offset().left;
      $("#operaLogBox").show();
      $("#operaLogBox").css({ "right": "30px", "top": (top + 20) + "px" })
    }, function () {
      $("#operaLogBox").hide();
    })

  });


  //增加、删除按钮
  function cLink(cellvalue, options, rowObject) {
    return '<div class="operating"><span class="ui-icon ui-icon-plus" title="新增行" onclick="add_row(' + options.rowId + ')" style="margin:0 2px;"></span> <span class="ui-icon ui-icon-trash" onclick="del_row(' + options.rowId + ')" title="删除行" style="margin:0 2px;">删除</span></div>';
  }


  // // 关闭仓库弹窗
  // function closeBatch() {
  //   $("#chooseBatch").hide();
  // }


  // 表头 批量按钮 点击样式
  function batchBtn(id) {
    $("#snapshotTipsBox").addClass("pcnone");
    if (id == 1) {
      $("#storageBox2").addClass('pcnone');
      $("#storageBox3").addClass('pcnone');
    } else if (id == 2) {
      $("#storageBox1").addClass('pcnone');
      $("#storageBox3").addClass('pcnone');
    } else if (id == 3) {
      $("#storageBox1").addClass('pcnone');
      $("#storageBox2").addClass('pcnone');
    }

    var top = $("#batchStorage" + id).offset().top;
    var left = $("#batchStorage" + id).offset().left;
    if ($("#storageBox" + id).hasClass("pcnone")) {
      $("#storageBox" + id).removeClass('pcnone');//removeClass
      $("#storageBox" + id).css({ 'left': (left - 25) + 'px', 'top': (top + 30) + 'px' });
    } else {
      $("#storageBox" + id).addClass('pcnone');
    }
  }
  // 点击弹窗确定按钮事件
  function closeStorage(id) {
    $("#storageBox" + id).addClass('pcnone');
  }

  // 点击表头可用库存
  function snapshotTipsFun() {
    // alert("AA")
    var top = $("#snapshotTipsBtn").offset().top;
    var left = $("#snapshotTipsBtn").offset().left;
    if ($("#snapshotTipsBox").hasClass("pcnone")) {
      $("#snapshotTipsBox").removeClass("pcnone");
      $("#snapshotTipsBox").css({ "top": (top + 30) + "px", "left": (left - 25) + "px" });
      $("#storageBox1").addClass('pcnone');
      $("#storageBox2").addClass('pcnone');
      $("#storageBox3").addClass('pcnone');
    } else {
      $("#snapshotTipsBox").addClass("pcnone");
    }

  }



  // 表头扫描枪录入的开关
  function smq() {

    if ($("#barCodeInsert").hasClass("close")) {
      $("#barCodeInsert").addClass('open');
      $("#barCodeInsert").removeClass('close');//removeClass

    } else {
      if ($("#barCodeInsert").hasClass("open")) {
        $("#barCodeInsert").addClass('close');
        $("#barCodeInsert").removeClass('open');//removeClass
      }
    }

  }


</script>

<script type="text/javascript">


  function getJQAllData() {
    //拿到grid对象
    var obj = $("#grid");
    //获取grid表中所有的rowid值
    var rowIds = obj.getDataIDs();
    //初始化一个数组arrayData容器，用来存放rowData
    var arrayData = new Array();

    if (rowIds.length > 0) {
      for (var i = 0; i < rowIds.length; i++) {
        if (Object.values(obj.getRowData(rowIds[i]))[2] != '') {
          arrayData.push(obj.getRowData(rowIds[i]));
        }
        //rowData=obj.getRowData(rowid);//这里rowid=rowIds[i];
        // console.log(obj.getRowData(rowIds[i].good_name));
        // return false;
        // if (obj.getRowData(rowIds[i].good_name != '')) {
        //   arrayData.push(obj.getRowData(rowIds[i]));
        // }
      }
    }
    return arrayData;
  }
</script>

<script type="text/javascript">
  var grid = $('#grid');

  $(".wrapper").on("click", "#savaAndAdd", function (e) {
    //先保存
    save_jqgrid(edit_row, edit_col, grid, function (res) {
      savedata(1);

    });
  })

  $(".wrapper").on("click", "#o_shenhe", function (e) {
    //先保存
    save_jqgrid(edit_row, edit_col, grid, function (res) {
      savedata(4);
      
    });
  })



  $(".wrapper").on("click", "#save", function (e) {
    save_jqgrid(edit_row, edit_col, grid, function (res) {
      $("#grid").jqGrid().trigger("reloadGrid");
      layer.msg("保存成功");
    });
  })
  //1.添加，2编辑，3复制，4，审核订单
  function savedata(type_btn) {

    //var gooddata = $('#grid').jqGrid('getGridParam', 'data');
    var gooddata = $('#grid').jqGrid('getRowData');
    var flag = 0;
    var hasuser = 0;
    var hasuser1 = 0;
    var indexArr = [];
    // console.log(gooddata);
    gooddata.forEach(function (self, index) {
      // console.log(self);
      if (self['good_id'] != null && self['good_id'] != "") {
        hasuser = hasuser + 1;
        if (self['store_id'] == null || self['store_id'] == "") {
          flag = 1;
          indexArr.push(index);
        } else {
          hasuser1 = hasuser1 + 1;
        }
      }
    });
    if (hasuser == 0) {
      layer.msg("请选择商品");
      // 必填项（商品）
      $("#grid").editCell(1, 3, true);
      return false;
    }

    if (flag == 1) {
      layer.msg("请选择仓库");
      // 必填项（仓库）
      $("#grid").editCell(indexArr[0]+1, 6, true);
      return false;
    }

    var customerid = $("#customerid").val();//客户ID
    if (customerid == "") {
      layer.msg('请先选择供应商');
      return false;
    }
    var movedata = getJQAllData();
    var dj_time = $("#dj_time").val();//单据日期
    var jh_time = $("#jh_time").val();//交货日期
    var sn = $("#number").html();//单据号
    var mark = $("#note").val();//备注
    var type = $('input:radio[name="type"]:checked').val();//业务类别
    var yh_lv = $("#yh_lv").val();//优惠率
    var yh_e = $("#yh_e").val();//优惠额
    var yh_price = $("#yh_price").val();//优惠后价格
    var before_yh_price = $("#before_yh_price").val();//优惠前价格
    if (type_btn == 1) {
      //新增
      var param = { before_yh_price: before_yh_price, user_id: customerid, sn: sn, mark: mark, movegood: movedata, dj_time: dj_time, jh_time: jh_time, yh_lv: yh_lv, yh_e: yh_e, yh_price: yh_price, type: type };
      var url = "/scm/invpo/save.html";
    } else if (type_btn == 4) {
      //直接审核
      var param = { o_shenhe: 1, before_yh_price: before_yh_price, user_id: customerid, sn: sn, mark: mark, movegood: movedata, dj_time: dj_time, jh_time: jh_time, yh_lv: yh_lv, yh_e: yh_e, yh_price: yh_price, type: type };
      var url = "/scm/invpo/save.html";

    }

    $.ajax({
      type: 'POST',
      url: url,
      data: param,
      dataType: "json",
      async: false,
      error: function (request) {
        layer.msg("发送请求失败！");
      },
      success: function (data) {
        if (data.status == 1) {
          layer.alert(data.msg, function () {
            if(type_btn==4 || type_btn==1){
              location.href="/scm/invpo/add.html";
            }else{
              location.reload();
            }
          });
        } else {
          layer.msg(data.msg);
        }

      }
    });

  }


</script>
{include file="admin@public/footer" /}